﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Citi.RoutineBase;
using Citi.Helpers;
using System.IO;

namespace Citi.GenericApplications.SchedulerUi
{
    public class JoinSheets : IExecutableRoutine
    {
        public IEnumerable<RoutineParameter> Parameters
        {
            get
            {
                return new List<RoutineParameter> { 
                    new RoutineParameter{ Description = "Excel path to join sheets", 
                        Name = "ExcelFile", Nullable = false, Required = true, Type = typeof(string)},
                    new RoutineParameter{ Description = "Pwd file. Only filename. E.g. ExcelPassword.pwd", 
                        Name ="PwdFile", Nullable = true, Required = false, Type = typeof(string)},
                    new RoutineParameter{ Description = "Path to save. If not provided the file will be replaced (.xlsx) or a .xlsx file will be created with the same name", 
                        Name ="PathToSaveJoinedFile", Nullable = true, Required = false, Type = typeof(string)}, 
                    new RoutineParameter{ Description = "All sheets named starting with this will be joined. If it not provided all sheets will be joined.", 
                        Name = "SheetsToMergeStartsWith", Nullable = true, Required = false, Type = typeof(string)},                                      
                    new RoutineParameter{ Description = "Provide a new sheet name", 
                        Name = "NewSheetName", Nullable= false, Required = true, Type = typeof(string)},                    
                    new RoutineParameter{ Description = "Header row number. If not provided the header will be consider at first row", 
                        Name ="HeaderRowNumber", Nullable = true, Required = false, Type = typeof(int)},
                    new RoutineParameter{ Description = "First column number. If not provided the header will be consider at first column.", 
                        Name ="FirstColumnNumber", Nullable = true, Required = false, Type = typeof(int)},
                    new RoutineParameter{ Description = "If you want to start a routine when it's finished, insert the Routine Id. Multiples routines: Separator pipe '|'", 
                        Name ="SuccessorRoutineId", Nullable = true, Required = false, Type = typeof(string)},
                    new RoutineParameter{ Description = "Delete original file after joining?", 
                        Name ="DeleteOriginalFile", Nullable = true, Required = false, Type = typeof(bool)}
                };
            }
        }

        public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            Util.KillExcelProcesses();
        }

        public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            var excelFile = parameters["ExcelFile"].ToString();
            var pwdFile = parameters.ContainsKey("PwdFile") ? parameters["PwdFile"].ToString() : null;
            var pathToSaveJoinedFile = parameters.ContainsKey("PathToSaveJoinedFile") ? parameters["PathToSaveJoinedFile"].ToString() : null;
            var newSheetName = parameters.ContainsKey("NewSheetName") ? parameters["NewSheetName"].ToString() : string.Empty;
            var successorRoutineId = parameters.ContainsKey("SuccessorRoutineId") ? parameters["SuccessorRoutineId"].ToString() : null;
            var headerRowNumber = parameters.ContainsKey("HeaderRowNumber") ? int.Parse(parameters["HeaderRowNumber"].ToString()) : 1;
            var firstColumnNumber = parameters.ContainsKey("FirstColumnNumber") ? int.Parse(parameters["FirstColumnNumber"].ToString()) : 1;
            var deleteOriginalFile = parameters.ContainsKey("DeleteOriginalFile") ? bool.Parse(parameters["DeleteOriginalFile"].ToString()) : false;
            var sheetsToMergeStartsWith = parameters.ContainsKey("SheetsToMergeStartsWith") ? parameters["SheetsToMergeStartsWith"].ToString() : null;

            if (string.IsNullOrWhiteSpace(pathToSaveJoinedFile))
                pathToSaveJoinedFile = excelFile;

            currentAction.Description = string.Format("Excel file: {0}", excelFile);

            if (!string.IsNullOrWhiteSpace(pwdFile))
                currentAction.Description = string.Format("Pwd file: {0}", pwdFile);

            currentAction.Description = string.Format("Sheets To Merge Starts With: {0}", sheetsToMergeStartsWith);
            currentAction.Description = string.Format("New Sheet Name: {0}", newSheetName);
            currentAction.Description = string.Format("Path to save joined file: {0}", pathToSaveJoinedFile);
            currentAction.Description = string.Format("Header Row Number: {0}", headerRowNumber);
            currentAction.Description = string.Format("First Column Number: {0}", firstColumnNumber);

            if (!string.IsNullOrWhiteSpace(successorRoutineId))
                currentAction.Description = string.Format("Sucessor routine Id: {0}", successorRoutineId);

            if (!File.Exists(excelFile) && File.Exists(pathToSaveJoinedFile))
                currentAction.Description = "Unmerged file doesn't exist and merged file already exists. Routine will continue without errors";
            else if (!File.Exists(excelFile))
                throw new FileNotFoundException("File does not exist");
            else
            {
                currentAction.Description = "Joining sheets";
                //var path = MergeExcel.MergeSheets(excelFile, pathToSaveJoinedFile, newSheetName, headerRowNumber, firstColumnNumber);
                currentAction.StartLog("Merging...");
                ExcelHelper.MergeSheets(excelFile, pathToSaveJoinedFile, sheetsToMergeStartsWith, newSheetName, headerRowNumber, firstColumnNumber);
                currentAction.StopLog();

                currentAction.Description = string.Format("Sheets joined. File saved: {0}", pathToSaveJoinedFile);

                if (deleteOriginalFile && File.Exists(pathToSaveJoinedFile))
                    File.Delete(excelFile);
            }

            Util.ScheduleSuccessorRoutine(successorRoutineId, currentAction);
        }

        public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            Util.KillExcelProcesses();
        }
    }
}
